class Admin::PostsController < Admin::ApplicationController
  before_action :find_post, only: %i{edit update move_trash}

  def index
    @posts = Post.order(id: :desc).page params[:page]
  end

  def new
    @post = Post.new post_category: PostCategory.new
  end


  def create
    @post = Post.new params.require(:post).permit(:title, :slug, :published_at, :body, post_category_attributes: [:category_id])
    if @post.save
      redirect_to admin_posts_url
    else
      render :new
    end
  end

  def edit
    @post.category ||= PostCategory.new
  end

  def update
    if @post.update params.require(:post).permit(:title, :slug, :published_at, :body, post_category_attributes: [:category_id])
      redirect_to admin_posts_url
    else
      render :edit
    end
  end

  def move_trash
    @post.move_trash
    render 'remove_post'
  end

  def index_trash
    @posts = Post.deleted.order(deleted_at: :desc).page params[:page]
  end

  def restore
    @post = Post.deleted.find params[:id]
    @post.restore
    render 'remove_post'
  end

  def destroy
    @post = Post.deleted.find params[:id]
    @post.destroy
    render 'remove_post'
  end

  private
  def find_post
    @post = Post.find params[:id]
  end
end
